package com.ksd.pug.config.interceptor.permission;

import com.ksd.pug.commons.anno.PugPermissionIngore;
import com.ksd.pug.commons.enums.ResultStatusEnumA;
import com.ksd.pug.commons.ex.PugValidationException;
import com.ksd.pug.commons.threadlocal.UserThrealLocal;
import com.ksd.pug.commons.utils.collection.CollectionUtils;
import com.ksd.pug.pojo.Permission;
import com.ksd.pug.pojo.SysLoginUser;
import com.ksd.pug.service.user.ISysLoginUserService;
import com.ksd.pug.utils.jwt.JwtTokenUtils;
import com.pug.redis.config.PugRedisCacheTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author hcl
 * 权限验证
 * @date 2022/3/3$ 10:09$
 */
@Component
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysLoginUserService sysLoginUserService;
    @Autowired
    private PugRedisCacheTemplate pugRedisCacheTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = cleanPath(request.getRequestURI());
        String token = JwtTokenUtils.getJwtToken(request);
        log.info("------------------------>permission------------>开始鉴权 : {}",uri);
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PugPermissionIngore annotation = handlerMethod.getBean().getClass().getAnnotation(PugPermissionIngore.class);
            PugPermissionIngore methodAnnotation = handlerMethod.getMethodAnnotation(PugPermissionIngore.class);
            log.info("------查看是否增加了---PugPermissionIngore-------{},{}",annotation,methodAnnotation);
            if (annotation != null || methodAnnotation != null) {
                log.info("------增加了---PugPermissionIngore---注解无需拦截-------");
                return true;
            }
        }

        // 开始获取用户对应的权限信息
        SysLoginUser sysLoginUser = UserThrealLocal.get();
        List<Permission> permissionList = pugRedisCacheTemplate.getCacheObject("sys:user:permission:list:" + token);
        if (CollectionUtils.isEmpty(permissionList)) {
            permissionList = sysLoginUserService.findBySysPermissionUserId(sysLoginUser.getId());
        }

        log.info("缓存获取权限成功：{}", permissionList);

        // 获取用户请求的方法
        Long count = permissionList.stream().filter(p -> uri.indexOf(p.getPath()) != -1).count();
        log.info("获取权限：{}", count);
        if (count == 0) {
            throw new PugValidationException(ResultStatusEnumA.NO_PERMISSION);
        }
        return true;
    }


    private static String cleanPath(String path) {
        if (path.indexOf("get/") != -1 || path.indexOf("delete/") != -1) {
            path = path.substring(0, path.lastIndexOf("/"));
        }
        return path;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
